import router from '@/router/index'
import Vue from 'vue'

const state = {
  list: [],
  selectedTag: {
    name: ''
  }
}

// 标签是否已经打开
const isOpened = (tag) => {
  let opened = false
  state.list.forEach((item) => {
    if (item.name === tag.name || item.meta.parent === tag.name) {
      opened = true
    }
  })
  return opened
}

const mutations = {
  // 添加标签到tagNav
  'addTag' (state, tag) {
    // 标签是否已经打开
    if (!isOpened(tag)) {
      // 当跳转到首页时，默认添加在第一位
      if (tag.name === 'home') {
        state.list.unshift(tag)
      } else {
        state.list.push(tag)
      }
    } else {
      state.list.forEach((item, index) => {
        if (item.name === tag.name || item.meta.parent === tag.name) {
          Vue.set(state.list, index, tag)
        }
      })
    }
    state.selectedTag = tag
  },

  // 进入嵌套内部路由切换
  'enterSubTag' (state, tag) {
    if (!isOpened(tag)) {
      state.list.forEach((item, index) => {
        if (item.name === tag.meta.parent || item.meta.parent === tag.meta.parent) {
          Vue.set(state.list, index, tag)
        }
      })
    }
    state.selectedTag = tag
  },
  // 关闭指定标签
  'closeTag' (state, name) {
    let closeIndex = -1
    let routerName = ''
    state.list.forEach((item, index) => {
      if (item.name === name) {
        closeIndex = index
      }
    })
    if (state.selectedTag.name === name) {
      // 如果当前选中关闭的标签是最后一个并且数量大于1，路由选中上一个
      if (closeIndex === state.list.length - 1) {
        routerName = state.list[closeIndex - 1].name
      } else {
        // 如果当前选中关闭的标签不是最后一个，路由选中下一个
        routerName = state.list[closeIndex + 1].name
      }
      router.push({ name: routerName })
    }
    if (closeIndex > -1) {
      state.list.splice(closeIndex, 1)
    }
  },

  // 关闭标签
  'closeBatchTag' (state, type) {
    if (type === 'all') {
      // type==='all'   则是关闭全部标签
      state.list = []
      router.push({ name: 'home' })
    } else {
      // type==='other' 则是关闭其他标签
      state.list = state.list.filter(item => item.name === state.selectedTag.name || item.meta.hasOwnProperty('fixed'))
    }
  },

}

const actions = {}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
